<template>
  <div class="app-container home">
    <el-row :gutter="20" style="height: auto">
      <!-- 左侧历史对话栏 -->
      <el-col :sm="8" :lg="4" style="height: calc(100vh - 84px)">
        <el-card class="history-container">
          <template #header>
            <div class="clearfix">
              <span>历史对话</span>
              <el-button
                type="primary"
                size="small"
                icon="Plus"
                style="float: right"
                @click="showCreateDialog"
                >新建
              </el-button>
            </div>
          </template>
          <el-scrollbar height="calc(100vh - 160px)">
            <div v-for="(group, date) in groupedChats" :key="date">
              <div class="date-divider">{{ date }}</div>
              <el-menu
                v-model="activeChatId"
                :default-active="String(activeChatId)"
                @select="handleChatSelect"
              >
                <el-menu-item
                  v-for="chat in group"
                  :key="chat.chatId"
                  :index="String(chat.chatId)"
                >
                  <template #title>
                    <div class="chat-item">
                      <el-tooltip
                        :content="chat.title"
                        placement="top-start"
                        :disabled="!isTitleOverflow(chat.title)"
                      >
                        <div class="chat-content">
                          <div class="chat-title">
                            {{ chat.title }}
                          </div>
                        </div>
                      </el-tooltip>
                      <el-dropdown trigger="click" @command="handleCommand">
                        <el-icon class="more-icon"><MoreFilled /></el-icon>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item
                              :command="{ type: 'rename', chat }"
                            >
                              <el-icon><Edit /></el-icon>重命名
                            </el-dropdown-item>
                            <el-dropdown-item
                              :command="{ type: 'delete', chat }"
                              style="color: #f56c6c"
                            >
                              <el-icon><Delete /></el-icon>删除
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </template>
                </el-menu-item>
              </el-menu>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 中间聊天框 -->
      <el-col :sm="16" :lg="12" style="height: calc(100vh - 84px)">
        <el-card class="chat-container" style="height: 100%">
          <template #header>
            <div class="clearfix">
              <span>DeepSeek 智能助手</span>
            </div>
          </template>
          <div class="chat-content">
            <div class="message-list">
              <div
                v-for="(msg, index) in messages"
                :key="index"
                class="message-item"
                :class="msg.role"
              >
                <div :class="['message-bubble', msg.role]">
                  <div
                    v-if="msg.role === 'assistant'"
                    v-html="renderMarkdown(msg.content)"
                  ></div>
                  <template v-else>{{ msg.content }}</template>
                </div>
              </div>
            </div>
            <div class="input-area">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="4"
                placeholder="请输入您的问题..."
                @keyup.enter="sendMessage"
              />
              <el-button
                @click="sendMessage"
                type="primary"
                style="margin-top: 10px; width: 100%"
              >
                <el-icon><Promotion /></el-icon> 发送
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧轮播图 -->
      <el-col :sm="24" :lg="8" style="height: calc(100vh - 84px)">
        <el-carousel :interval="3000" height="100%" arrow="always">
          <el-carousel-item
            v-for="(item, index) in banners"
            :key="index"
            style="height: 100%"
          >
            <img
              :src="item.imgUrl"
              class="banner-img"
              :alt="item.title"
              style="height: 100%"
            />
            <div class="banner-title">{{ item.title }}</div>
          </el-carousel-item>
        </el-carousel>
      </el-col>
    </el-row>

    <!-- 新建对话弹窗 -->
    <el-dialog v-model="open" :title="openTitle" width="500" append-to-body>
      <el-form :model="form" label-width="80px" ref="chatRef" :rules="rules">
        <el-form-item label="对话标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入对话标题" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="createNewChat">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listChat, addChat, updateChat, delChat, getChat } from '@/api/manage/chat'
import { parseTime } from '@/utils/ruoyi'
import useUserStore from '@/store/modules/user'
import { getToken } from "@/utils/auth"
// 引入图片资源
import banner1 from '@/assets/images/banner-1.jpg'
import banner2 from '@/assets/images/banner-2.jpg'
import banner3 from '@/assets/images/banner-3.jpg'
import { marked } from 'marked' // 添加markdown解析库

const userStore = useUserStore()
const baseUrl = import.meta.env.VITE_APP_BASE_API
// const messages = ref([
//   { role: 'assistant', content: '您好！我是DeepSeek智能助手，请问有什么可以帮助您的？' }
// ])
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const banners = ref([
  { imgUrl: banner1 },
  { imgUrl: banner2 },
  { imgUrl: banner3 }
])

// 新增状态管理
const chatList = ref([])
const activeChatId = ref(null)
const activeChat = ref(null)
const open = ref(false)
const openTitle = ref("")

const data = reactive({
  form: {},
  rules: {
    title: [
      { required: true, message: '请输入对话标题', trigger: 'blur' }
    ]
  }
})
const { proxy } = getCurrentInstance()
const { form, rules } = toRefs(data)

// 修改sendMessage函数
async function sendMessage() {
  if (!inputMessage.value.trim()) return

  // 用户消息 - 使用新数组确保响应式更新
  const userMessage = { role: 'user', content: inputMessage.value }
  messages.value = [...messages.value, userMessage]

  // 助手消息占位 - 初始为空
  const assistantMessage = { role: 'assistant', content: '' }
  messages.value = [...messages.value, assistantMessage]

  inputMessage.value = ''
  isLoading.value = true

  try {
    const requestData = {
      model: 'deepseek-chat',
      messages: messages.value.slice(0, -1), // 排除刚添加的assistant占位消息
      stream: true
    }

    const response = await fetch(baseUrl + '/deepseek/chat/stream', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + getToken(),
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''

    while (true) {
      const { value, done } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })

      // 处理可能的多条消息合并情况
      const parts = buffer.split('\n')
      buffer = parts.pop() || '' // 保留未完成的部分

      for (const line of parts) {
        const trimmedLine = line.trim()
        if (!trimmedLine.startsWith('data:')) continue

        const jsonStr = trimmedLine.replace(/^data:\s*/, '')
        if (jsonStr === '[DONE]') continue

        try {
          const data = JSON.parse(jsonStr)
          const content = data?.choices?.[0]?.delta?.content
          if (content !== undefined) {
            // 直接更新最后一条消息的内容
            const lastMsgIndex = messages.value.length - 1
            messages.value[lastMsgIndex].content += content

            // 强制触发响应式更新
            messages.value = [...messages.value]
          }
        } catch (err) {
          console.error('JSON解析失败:', err, line)
        }
      }
    }

    // 在AI回复完成后，检查是否需要创建新对话
    if (!activeChatId.value) {
      await createAutoChat(messages.value)
    } else {
      await updateChatMessages()
    }
  } catch (err) {
    console.error('流式请求失败:', err)
    const lastMsgIndex = messages.value.length - 1
    messages.value[lastMsgIndex].content = '请求失败，请稍后再试'
    messages.value = [...messages.value] // 强制更新
  } finally {
    isLoading.value = false
  }
}

// 修改自动创建对话函数
async function createAutoChat(messages) {
  try {
    // 使用第一条用户消息的前5个字符作为默认标题
    const response = await addChat({
      messageBody: JSON.stringify(messages)
    })
    
    if (response.code === 200) {
      await fetchChatList()
    }
  } catch (err) {
    proxy.$modal.msgError("自动创建对话失败")
  }
}

// 在模板中使用v-html渲染markdown
const renderMarkdown = (content) => {
  return marked(content)
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    title: null
  }
  proxy.resetForm("chatRef")
}

// 获取历史对话列表
async function fetchChatList() {
  try {
    const res = await listChat()
    chatList.value = res.data.map(chat => ({
      ...chat,
      // 这里不再解析messageBody，改为点击时再获取
      messages: []
    }))
    // 移除自动加载第一条对话的逻辑
  } catch (err) {
    console.error('获取对话列表失败:', err)
  }
}

// 在loadChatMessages函数中添加保存逻辑
async function loadChatMessages (chatId) {
  const chat = chatList.value.find(c => c.chatId === chatId)
  if (chat) {
    activeChat.value = chat
    messages.value = chat.messages
    if (messages.value.length === 0) {
      messages.value = [
        { role: 'assistant', content: '您好！我是DeepSeek智能助手，请问有什么可以帮助您的？' }
      ]
      // 初始化时也保存默认欢迎语
      // await updateChatMessages()
    }
  }
}

// 修改createNewChat函数
async function createNewChat () {
  proxy.$refs["chatRef"].validate(valid => {
    if (valid) {
      if (form.value.chatId != null) {
        updateChat(form.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("重命名成功")
            // 更新chatList中的title
            const index = chatList.value.findIndex(c => c.chatId === form.value.chatId)
            if (index !== -1) {
              chatList.value[index].title = form.value.title
            }
          }
          open.value = false
        })
      } else {
        addChat(form.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("新增成功")
            fetchChatList()
          }
          open.value = false
        })
      }
    }
  })
}

// 修改handleChatSelect函数
async function handleChatSelect(chatId) {
  activeChatId.value = Number(chatId)
  try {
    const res = await getChat(chatId)
    if (res.code === 200) {
      const chat = res.data
      activeChat.value = chat
      messages.value = chat.messageBody ? JSON.parse(chat.messageBody) : []
    }
  } catch (err) {
    proxy.$modal.msgError('获取对话详情失败')
  }
}

// 显示新建对话弹窗
function showCreateDialog () {
  open.value = true
  openTitle.value = '新建对话'
}

// 新增updateChatMessages函数
async function updateChatMessages () {
  // if (!activeChatId.value) return
  try {
    await updateChat({
      chatId: activeChatId.value,
      messageBody: JSON.stringify(messages.value)
    })
  } catch (err) {
    console.error('保存对话失败:', err)
  }
}

// 添加handleCommand函数
function handleCommand (command) {
  if (command.type === 'rename') {
    open.value = true
    openTitle.value = '重命名对话'
    form.value = {
      title: command.chat.title,
      chatId: command.chat.chatId
    }
  } else if (command.type === 'delete') {
    deleteChat(command.chat.chatId)
  }
}

// 添加deleteChat函数
function deleteChat (chatId) {
  proxy.$modal.confirm('确定删除该对话吗？').then(function () {
    return delChat(chatId)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功')
    fetchChatList().then(() => {
      // 如果删除的是当前选中的对话
      if (activeChatId.value === chatId) {
        // 选中第一个对话（如果有）
        if (chatList.value.length > 0) {
          // 清空消息
          messages.value = []
          activeChatId.value = null
          activeChat.value = null
        }
      }
    })
  }).catch(() => { })
}

const groupedChats = computed(() => {
  const groups = {}
  chatList.value.forEach(chat => {
    const date = parseTime(chat.createTime, '{y}年{m}月{d}日')
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(chat)
  })
  return groups
})

// 判断标题是否溢出需要显示tooltip
function isTitleOverflow (title) {
  // 这里可以根据实际需求调整判断逻辑
  return title && title.length > 6 // 假设超过15个字符显示tooltip
}

fetchChatList()
</script>

<style scoped lang="scss">
.history-container {
  height: 100%;
  border-radius: 8px;

  :deep(.el-card__header) {
    padding: 12px 20px;
  }

  :deep(.el-menu) {
    border-right: none;
  }
}

.chat-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;

  .chat-content {
    flex: 1;
    min-width: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .chat-title {
    font-size: 14px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: calc(100% - 40px); // 减去更多按钮的宽度
    justify-content: space-between;
  }

  .more-icon {
    cursor: pointer;
    padding: 4px;
    flex-shrink: 0;
    margin-left: 8px;
    &:hover {
      color: var(--el-color-primary);
    }
  }
}

:deep(.el-menu-item) {
  padding: 0 10px 0 0;
  line-height: normal;
  border-radius: 12px;
  margin: 2px 0;

  &.is-active {
    background-color: #f0f7eb !important;
    color: #67c23a !important;
  }

  &:hover {
    background-color: #f5f7fa;
  }
}

.date-divider {
  padding: 8px 16px;
  font-size: 14px;
  color: #666;
  font-weight: bold;
  margin: 8px 0 4px 0;
  border-radius: 4px;
}

// 确保菜单项选中状态不会被覆盖
:deep(.el-menu) {
  --el-menu-active-color: #67c23a;
  --el-menu-item-height: 40px;

  .el-menu-item {
    &.is-active {
      background-color: #f0f7eb !important;
    }
  }
}

.home {
  height: auto; // 修改为auto

  .chat-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    overflow: hidden;
    position: relative;

    :deep(.el-card__header) {
      background-color: #f8f8f8;
      border-bottom: 1px solid #eaeaea;
      padding: 12px 20px;
      font-weight: 500;
    }

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0;
      height: 100%;
    }

    .chat-content {
      display: flex;
      flex-direction: column;
      height: 100%;
      padding: 0;

      .message-list {
        flex: 1;
        overflow-y: auto;
        padding-right: 16px;
        display: flex;
        flex-direction: column;
        gap: 16px;
        padding-bottom: 160px;

        .message-item {
          display: flex;
          flex-direction: column;

          &.user {
            align-items: flex-end;
            margin-left: auto;
            width: 100%;
          }

          &.assistant {
            align-items: flex-start;
          }

          .message-bubble {
            max-width: 85%;
            min-width: 60px;
            padding: 8px 16px;
            border-radius: 12px;
            line-height: 1.6;
            word-break: break-word;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            position: relative;

            &.user {
              background-color: #67c23a;
              color: white;
              border-bottom-right-radius: 4px;
              max-width: fit-content;
              margin-left: auto;
              margin-right: 0;
            }

            &.assistant {
              background-color: #f5f7fa;
              color: #333;
              border-bottom-left-radius: 4px;
              padding: 2px 16px;

              :deep(p) {
                margin: 0.5em 0;
              }
            }
          }
        }
      }

      .input-area {
        position: sticky;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 16px;
        border-top: 1px solid #eaeaea;
        background-color: #f8f8f8;
        z-index: 10;

        :deep(.el-textarea__inner) {
          border-radius: 8px;
          resize: none;
          box-shadow: none;
          border: 1px solid #dcdfe6;

          &:focus {
            border-color: #67c23a;
          }
        }
      }
    }
  }

  .banner-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .banner-title {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    color: white;
    font-size: 24px;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8);
  }

  .el-carousel {
    height: 100%;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    :deep(.el-carousel__container) {
      height: 100%;
    }
  }
}
</style>
